package com.agent.payment.service;

import com.agent.membership.api.feign.MembershipFeignClient;
import com.agent.payment.entity.PaymentCallbackLog;
import com.agent.common.entity.UserContext;
import com.agent.common.exception.BusinessException;
import com.agent.common.exception.PaymentException;
import com.agent.common.result.ResultCode;
import com.agent.common.utils.IdGenerator;
import com.agent.payment.entity.PaymentOrder;
import com.agent.payment.mapper.PaymentCallbackLogMapper;
import com.agent.payment.mapper.PaymentOrderMapper;
import com.agent.user.api.feign.UserFeignClient;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.ZoneOffset;

/**
 * 支付核心服务
 * @author Jeff_Wan
 * @description 处理支付订单创建、回调处理等核心逻辑
 */
@Service
@RequiredArgsConstructor
public class PaymentService {
    private final PaymentOrderMapper paymentOrderMapper;
    private final PaymentCallbackLogMapper paymentCallbackLogMapper;
    private final AsiabillService asiabillService;
    private final PaypalService paypalService;
    private final MembershipFeignClient membershipFeignClient;
    private final UserFeignClient userFeignClient;
    private final IdGenerator idGenerator = IdGenerator.getInstance();
    
    /**
     * 创建支付订单
     * @param userContext 用户上下文
     * @param planType 套餐类型
     * @param subscriptionType 订阅类型
     * @param paymentMethod 支付方式
     * @param creditConversion 积分抵扣金额
     * @return 支付订单对象
     */
    @Transactional
    public PaymentOrder createPaymentOrder(UserContext userContext, String planType, 
                                          String subscriptionType, String paymentMethod, 
                                          BigDecimal creditConversion) {
        // 验证用户信息
        if (userContext == null || userContext.getUserId() == null) {
            throw new BusinessException(ResultCode.USER_NOT_LOGIN);
        }
        
        // 计算支付金额
        BigDecimal amount = calculatePlanAmount(planType, subscriptionType);
        if (creditConversion != null && creditConversion.compareTo(BigDecimal.ZERO) > 0) {
            amount = amount.subtract(creditConversion);
            if (amount.compareTo(BigDecimal.ZERO) < 0) {
                amount = BigDecimal.ZERO;
            }
        }
        
        // 创建支付订单
        PaymentOrder order = new PaymentOrder();
        order.setId(idGenerator.nextId());
        order.setUserId(userContext.getUserId());
        order.setOrderNumber(generateOrderNumber());
        order.setAmount(amount);
        order.setCurrency("USD");
        order.setPaymentMethod(paymentMethod);
        order.setPaymentStatus("PENDING");
        order.setPlanType(planType);
        order.setSubscriptionType(subscriptionType);
        order.setOriginalPlan(userContext.getMembershipType());
        order.setCreditConversion(creditConversion);
        
        // 设置UTC时间
        order.setCreatedAt(LocalDateTime.now(ZoneOffset.UTC));
        order.setUpdatedAt(LocalDateTime.now(ZoneOffset.UTC));
        
        paymentOrderMapper.insert(order);
        
        return order;
    }
    
    /**
     * 处理支付回调
     * @param paymentMethod 支付方式
     * @param callbackData 回调数据
     * @param signature 签名
     * @return 处理结果
     */
    @Transactional
    public boolean handlePaymentCallback(String paymentMethod, String callbackData, String signature) {
        // 记录回调日志
        PaymentCallbackLog log = new PaymentCallbackLog();
        log.setId(idGenerator.nextId());
        log.setCallbackData(callbackData);
        log.setSignature(signature);
        log.setCreatedAt(LocalDateTime.now(ZoneOffset.UTC)); // UTC时间
        
        try {
            boolean isValid = false;
            String orderNumber = null;
            
            // 根据支付方式处理回调
            if ("ASIABILL".equalsIgnoreCase(paymentMethod)) {
                isValid = asiabillService.verifyCallback(callbackData, signature);
                orderNumber = asiabillService.parseOrderNumber(callbackData);
            } else if ("PAYPAL".equalsIgnoreCase(paymentMethod)) {
                isValid = paypalService.verifyCallback(callbackData, signature);
                orderNumber = paypalService.parseOrderNumber(callbackData);
            }
            
            if (!isValid || orderNumber == null) {
                log.setProcessed(false);
                return false;
            }
            
            // 查询订单
            PaymentOrder order = paymentOrderMapper.findByOrderNumber(orderNumber);
            if (order == null) {
                log.setProcessed(false);
                return false;
            }
            
            log.setOrderId(order.getId());
            
            // 更新订单状态
            order.setPaymentStatus("SUCCESS");
            order.setTransactionId(extractTransactionId(callbackData));
            order.setUpdatedAt(LocalDateTime.now(ZoneOffset.UTC)); // UTC时间
            paymentOrderMapper.updateById(order);
            
            // 调用会员服务升级会员
            membershipFeignClient.upgradeMembership(
                order.getUserId(), 
                order.getPlanType(), 
                order.getSubscriptionType(),
                order.getOriginalPlan(),
                order.getCreditConversion()
            );
            
            log.setProcessed(true);
            return true;
        } catch (Exception e) {
            log.setProcessed(false);
            throw new PaymentException(ResultCode.PAYMENT_GATEWAY_ERROR, "Payment callback processing failed: " + e.getMessage());
        } finally {
            paymentCallbackLogMapper.insert(log);
        }
    }

    /**
     * 通过ID获取订单
     * @param orderId 订单ID
     * @return 订单对象
     */
    public PaymentOrder getOrderById(Long orderId) {
        return paymentOrderMapper.selectById(orderId);
    }
    
    /**
     * 计算套餐金额
     * @param planType 套餐类型
     * @param subscriptionType 订阅类型
     * @return 支付金额
     */
    private BigDecimal calculatePlanAmount(String planType, String subscriptionType) {
        // 根据需求文档中的价格计算
        if ("BASIC".equals(planType)) {
            if ("MONTHLY".equals(subscriptionType)) {
                return BigDecimal.valueOf(9.9);
            } else {
                return BigDecimal.valueOf(100);
            }
        } else if ("PRO".equals(planType)) {
            if ("MONTHLY".equals(subscriptionType)) {
                return BigDecimal.valueOf(29.9);
            } else {
                return BigDecimal.valueOf(300);
            }
        } else if ("MAX".equals(planType)) {
            if ("MONTHLY".equals(subscriptionType)) {
                return BigDecimal.valueOf(49.9);
            } else {
                return BigDecimal.valueOf(540); // 年计划: 49.9*12=598.8, 实际年费540
            }
        }
        throw new BusinessException(ResultCode.INVALID_SUBSCRIPTION_PLAN);
    }
    
    /**
     * 生成订单号
     * @return 唯一订单号
     */
    private String generateOrderNumber() {
        return "PAY" + System.currentTimeMillis() + (int)(Math.random() * 1000);
    }
    
    /**
     * 从回调数据中提取交易ID
     * @param callbackData 回调数据
     * @return 交易ID
     */
    private String extractTransactionId(String callbackData) {
        // 实际实现需要解析回调数据
        return "TXN" + System.currentTimeMillis();
    }
}